package com.cuanbobox.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Environment;
import android.view.View;
import com.cuanbobox.base.App;
import com.cuanbobox.bean.AtyInfo;
import java.util.Date;

/**
 * 截图工具类
 */
public class CaptureUtil {
    /**
     * 记录需要截图时的时间
     */
    public static long recordTime = 0;

    /**
     * 获取Activity的截图
     *
     * @param aty Activity对象
     * @return 位图对象
     */
    public static Bitmap getCaptureBitmap(Activity aty) {
        if (aty == null) return null;
        Bitmap bitmap = null;
        try {
            View decorView = aty.getWindow().getDecorView();
            decorView.setDrawingCacheEnabled(true);
            bitmap = Bitmap.createBitmap(decorView.getDrawingCache());
            decorView.setDrawingCacheEnabled(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 记录需要截图的时间
     */
    public static void recordTime() {
        recordTime = new Date().getTime();
        LogUtil.add("记录时间", "" + recordTime, "截图");
    }

    /**
     * 截图
     */
    public static void capture() {
        //if (recordTime <= 0) return;
        try {
            //long diff = new Date().getTime() - recordTime;
            //if (diff < 100) return;
            //recordTime = 0;
            AtyInfo atyInfo = App.getShowingActivity();
            LogUtil.add("准备截图", "要截取的Activity界面=" + atyInfo.getAty().getClass().getSimpleName(), "截图", false);
            if (atyInfo != null) {
                Bitmap bitmap = getCaptureBitmap(atyInfo.getAty());
                String path = App.getInstance().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/html/img/capture.jpg";
                LogUtil.add("准备截图", "保存地址=" + path + " bitmap=" + bitmap, "截图", false);
                BitmapUtil.saveJPG(path, bitmap);
            } else {
                LogUtil.add("截图失败", "没有显示在前台的Activity! atyInfo=" + atyInfo, "截图");
            }
        }catch (Exception e){}
    }

}
